<?php
class RPC {
	public $request;
	public $request_decoded;

	public $response = array();

	public $errors = array();

	public static $instance;

	public static function _getInstance() {
		if(!self::$instance)
			self::$instance = new RPC();
		return self::$instance;
	}
	function init() {
	//request is post
	$HTTP_RAW_POST_DATA = file_get_contents("php://input");
		self::_getInstance()->request = stripslashes(isset($HTTP_RAW_POST_DATA)&&$HTTP_RAW_POST_DATA?
			$HTTP_RAW_POST_DATA:
			(isset($_GET['data'])?$_GET['data']:false));

		self::_getInstance()->request_decoded = json_decode( self::_getInstance()->request,true);

		if(!is_array( self::_getInstance()->request_decoded) && !is_object( self::_getInstance()->request_decoded))
			self::_getInstance()->addError(1,'NO_REQUEST');
		if(isset($this->request_decoded->data))
			$this->request_decoded = $this->request_decoded->data;

			if(isset($this->request_decoded['data']))
			$this->request_decoded = $this->request_decoded['data'];

	

	}

	public function addError($n,$txt = '') {
		self::_getInstance()->errors[] = array($n,$txt);
	}

	public function process() {
		if(! self::_getInstance()->validate()) {
			self::_getInstance()->addError(2,'AUTH');
			return false;
		}

		switch ( self::_getInstance()->get('action')) {
			case 'init' :
				PlayerController::Init();
				break;
			case 'get_rooms' :
				RoomsController::getAllRooms();
				break;
			default:
				self::_getInstance()->addError(3,'ILLEGAL_ACTION');
				break;
		}
	}

	public function get($field,$def = false) {
		if(isset( self::_getInstance()->request_decoded[$field]))
			return  self::_getInstance()->request_decoded[$field];
		return $def;
	}

	public function set() {

	}

	public function validate() {
		$uid =  self::_getInstance()->get('user_id');
		if(!$uid)
			$uid =  self::_getInstance()->get('network_user_id');

		$hash =  self::_getInstance()->get('secret');
		$md5 = md5(conf::$api_id.'_'.$uid.'_'.conf::$api_secret);
		if($md5 === $hash) {
			return true;
		}
		else {
			return false;
		}
	}

	public function addResponse($field, $data) {
		self::_getInstance()->response[$field] = $data;
	}

	public function response() {
		$response = new StdClass();
		if(count( self::_getInstance()->errors)) {
			foreach( self::_getInstance()->errors as $error) {
				$response->errors[] = $error;
			}
		}
		else {
			if(count( self::_getInstance()->response)) {
				foreach( self::_getInstance()->response as $field => $value) {
					$response->$field = $value;
				}
			}
		}
		return $response;
	}
}